package com.shhm.exception;

import com.shhm.common.dto.response.AjaxResultPlus;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.SocketException;
import java.sql.SQLException;

/**
 * @author JackZ
 * @version 1.0
 * @description: TODO
 * @date 2025/9/2 下午4:44
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 处理原生SQL异常
    @ExceptionHandler(SQLException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResultPlus handleSQLException(SQLException e) {
        System.out.println("异常码:"+e.getErrorCode()+",异常信息："+e.getMessage());
//        System.out.println("详细异常信息："+e);
        return AjaxResultPlus.error("操作失败，请刷新页面或稍后重试！");
    }

    // 处理令牌过期异常
    @ExceptionHandler(ExpiredJwtException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public AjaxResultPlus handleSQLException(ExpiredJwtException e) {
//        log.error("SQL执行异常: [{}] {}", e.getErrorCode(), e.getMessage(), e);
        return AjaxResultPlus.custom(401,true)
                .put("message", "账号登录信息过期，请重新登录！");
    }

    // 捕获数据库连接失败、连接超时等异常
    @ExceptionHandler({DataAccessResourceFailureException.class, CannotAcquireLockException.class})
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    public AjaxResultPlus handleDatabaseConnectionFailure() {
        return AjaxResultPlus.custom(503,true)
                .put("message", "数据库连接异常，请稍后重试!");
    }

    // 捕获所有数据库访问异常
//    @ExceptionHandler(DataAccessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResultPlus handleDatabaseAccessException(DataAccessException ex) {
        return AjaxResultPlus.custom(500,true)
                .put("message", "数据库操作异常!");
    }

    // 捕获所有数据库访问异常
//    @ExceptionHandler(SocketException.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    public AjaxResultPlus handleRedisConnectionException(DataAccessException ex) {
//        return AjaxResultPlus.custom(500,true)
//                .put("message", "缓存连接异常，请稍后重试!!");
//    }

    // 处理令牌过期异常
//    @ExceptionHandler(Exception.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    public AjaxResultPlus handleSQLException(Exception e) {
////        log.error("SQL执行异常: [{}] {}", e.getErrorCode(), e.getMessage(), e);
//        return AjaxResultPlus.custom(401,true)
//                .put("message", "啊噢，服务貌似发生异常！");
//    }
}
